package cn.deepmax.spring.cloud.system.mall.service.impl;

import cn.deepmax.spring.cloud.common.web.AjaxResponse;
import cn.deepmax.spring.cloud.system.mall.service.RemoteService;
import cn.deepmax.spring.cloud.system.mall.vo.Product;
import cn.deepmax.spring.cloud.system.mall.vo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class RemoteServiceImpl implements RemoteService {

    @Autowired
    private RestTemplate restTemplate;
    public static final String USER_SERVICE = "user-system";
    public static final String USER_GET = "http://"+USER_SERVICE+"/user/{id}.json";
    public static final String PRODUCT_SERVICE = "product-system";
    public static final String PRODUCT_GET = "http://product-system/product/{id}.json";


    @HystrixCommand(fallbackMethod = "getUserFallback")
    @Override
    public User getUser(Long id){
        Map<String,Object> param = new HashMap<>();
        param.put("id",id);
        ParameterizedTypeReference<AjaxResponse<User>> type = new ParameterizedTypeReference<AjaxResponse<User>>(){};
        ResponseEntity<AjaxResponse<User>> result = restTemplate.exchange(USER_GET, HttpMethod.GET, null, type, param);

        return result.getBody().getData();

    }

    public User getUserFallback(Long id){
        log.error("Hytrix fallback for getUser id = {}",id);
        User user = new User();
        user.setId(id);
        user.setName("DUMMY");
        return user;
    }

    @HystrixCommand(fallbackMethod = "getProductFallback")
    @Override
    public Product getProduct(Long id) {
        Map<String,Object> param = new HashMap<>();
        param.put("id",id);
        ParameterizedTypeReference<AjaxResponse<Product>> type = new ParameterizedTypeReference<AjaxResponse<Product>>(){};
        ResponseEntity<AjaxResponse<Product>> result = restTemplate.exchange(PRODUCT_GET, HttpMethod.GET, null, type, param);
        return result.getBody().getData();

    }

    public Product getProductFallback(Long id){
        log.error("Hystrix fallback for getProductFallback id = {}",id);
        Product product = new Product();
        product.setId(id);
        product.setName("DUMMY PRODUCT");
        product.setBrand("SimpleTour");
        return product;
    }
}
